package Server;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import Data.CriminalRecord;
import Data.MissingRecord;
import Data.Record;

public class UDPThread extends Thread{

	private StationServerImpl stationServerImpl;
	int portnumber;
	String recordID, fName, lName, status, desc, badgeID, addr, lDate, lastLoc;
	
	DatagramSocket aSocket;
	
	public UDPThread(StationServerImpl stationServerImpl, int i) {
		// TODO Auto-generated constructor stub
		this.stationServerImpl=stationServerImpl;
		this.portnumber=i;
	}
	public void run()
	{
		
	System.out.println("In UDP Thread now\n");
	
	System.out.println("Current Port in UDP Thread : " +this.portnumber + "\n\n");
	System.out.println("Thread : " + this.portnumber + " :  " + this.getId());
	
		try{

			byte [] receivedData = new byte[55]; // received data from other servers
			byte [] dataToSend = new byte[55]; // data sent to other servers
			aSocket = new DatagramSocket(portnumber);
			
			while(true){
				aSocket = new DatagramSocket(portnumber);
				
				DatagramPacket request = new DatagramPacket(receivedData,receivedData.length);
				System.out.println("1\n\n");
				aSocket.receive(request);
				System.out.println("2\n\n");			
				String s=new String(request.getData()).trim();
								
				StringTokenizer st = new StringTokenizer(s, "|");
				recordID = st.nextToken();
				fName = String.valueOf(st.nextToken());
				lName = String.valueOf(st.nextToken());
				status = String.valueOf(st.nextToken());
				
				// check the record for criminal or missing record and then create the record accordingly.
				
				if(recordID.startsWith("CR")) {
					
					Record tr= new CriminalRecord(recordID, fName, lName, status, null, null); 
					
					Character c = lName.charAt(0);
					if(stationServerImpl.chashtable.containsKey(lName.charAt(0)))
					{
						List<Record> existingList = stationServerImpl.chashtable.get(lName.charAt(0));
						
						synchronized(existingList) // synchronize the existing list for that particular character   
						{
							existingList.add(tr); // add the record to the existing list
							stationServerImpl.chashtable.put(c, existingList); 
						}
					} // end of if loop
					
				// else we create a new list with the first character of the last name of the criminal and then add it to the chashtable
					else
					{
						List<Record> newList = new ArrayList<Record>();
						synchronized (newList) // synchronize the newly created list and add the record to this newlist
						{
							newList.add(tr);
							stationServerImpl.chashtable.put(c, newList);	// insert the new list to the chashtable				
						}
					}// end of else
					
				} // end of record starting with "CR"
				
				if((recordID.startsWith("MR"))) {
					
				Record tr= new MissingRecord(recordID, fName, lName, null, null, null, status, null); 
				
				Character c = lName.charAt(0);
				if(stationServerImpl.chashtable.containsKey(lName.charAt(0)))
				{
					List<Record> existingList = stationServerImpl.chashtable.get(lName.charAt(0));
					
					synchronized(existingList) // synchronize the existing list for that particular character   
					{
						existingList.add(tr); // add the record to the existing list
						stationServerImpl.chashtable.put(c, existingList); 
					}
				} // end of if loop
				
			// else we create a new list with the first character of the last name of the criminal and then add it to the chashtable
				else
				{
					List<Record> newList = new ArrayList<Record>();
					synchronized (newList) // synchronize the newly created list and add the record to this newlist
					{
						newList.add(tr);
						stationServerImpl.chashtable.put(c, newList);	// insert the new list to the chashtable				
					}
				}// end of else
				
				} // end if records starting with "MR"
				
				System.out.println("\n In UDP Thread values: "+ recordID +" "+ fName +  " " + lName + " " + status + "\n");
				
				String c = " Record is transferred";
				dataToSend=c.getBytes();
				
				DatagramPacket response = new DatagramPacket(dataToSend, portnumber);
				aSocket.send(response);
				System.out.println("Data at UDP SPVM:   " + s );
				
			//	DatagramPacket reply= new DatagramPacket(dataToSend,dataToSend.length,request.getAddress(),request.getPort());
			//	aSocket.send(reply);
				
				} // end of while(true)
			
		}// end of try block
		catch(Exception e)
		{
			aSocket.close();
		}
		 
		finally{
			if(aSocket!= null ){
				
				aSocket.close();
		} // end of if block
		} // end of finally block 	

	}
	
}
